﻿using Mysqlx.Crud;
using Mysqlx.Prepare;
using OfficeOpenXml;
using PCHMI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ToolBar;
using LicenseContext = OfficeOpenXml.LicenseContext;





namespace 建邦配料系统
{

    public partial class Main : Form
    {
       // private readonly string excelFilePath;

        private TC_ScaleTcpClient TC_scaleClient = new TC_ScaleTcpClient();
        private SMQ_ScaleTcpClient SMQ_scaleClient = new SMQ_ScaleTcpClient();
        int I;

        private static bool JudgeRange=false;//新增：用来判断提示累计重量首次到达合格范围与首次超过合格范围变量
        private float total_weight=0;//定义一个变量来存储“累计重量”

        public Main()
        {
            InitializeComponent();
            SetupEvents();
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;

            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;//设置ExcelPackage的许可证


            //新增：为两个文本框绑定文本变化事件
            textBox_Name.TextChanged += TextBox_TextChanged;
            textBox_Batter.TextChanged += TextBox_TextChanged;

            button9.Enabled = false;
            button1.Enabled = false;
            button_Save.Enabled = false;
        }

        //wenben
        private void TextBox_TextChanged(object sender, EventArgs e)
        {
            Check();
        }

        //
        private void SetupEvents()
        {
            TC_scaleClient.DataReceived += data =>
            {
                this.Invoke(new MethodInvoker(() => txtLog.AppendText($"台秤接收: {data}{Environment.NewLine}")));
                if (data.Split(' ')[0] == "S")
                {
                    switch (data.Split(' ')[1])
                    {
                        case "S":
                            label31.Text = "（稳定）";
                            label1.Text = data.Replace(" ", "").Split('S')[2];
                            break;
                        case "D":
                            label31.Text = "（动态）";
                            label1.Text = data.Replace(" ", "").Split('D')[1];
                            break;
                        case "+":
                            label1.Text = "秤台超载";
                            break;
                        case "-":
                            label1.Text = "秤台欠载";
                            break;
                    }
                }
                if (data.Split(' ')[0] == "T")
                {
                    switch (data.Split(' ')[1])
                    {
                        case "S":
                            label_Tare.Text = data.Replace(" ", "").Split('S')[1];
                            break;
                        case "I":
                            label1.Text = "稳态去皮失败";
                            break;
                        case "+":
                            label1.Text = "超出去皮范围上限，稳态去皮命令无法执行";
                            break;
                        case "-":
                            label1.Text = "超出去皮范围上限，稳态去皮命令无法执行";
                            break;
                    }
                }
            };

            TC_scaleClient.LogMessage += msg =>
                this.Invoke(new MethodInvoker(() => txtLog.AppendText($"[日志] {msg}{Environment.NewLine}")));

            SMQ_scaleClient.DataReceived += data =>
                this.Invoke(new MethodInvoker(() => txtLog.AppendText($"扫码枪接收: {data}{Environment.NewLine}")));

            SMQ_scaleClient.DataReceived += data =>
                this.Invoke(new MethodInvoker(() => SMQ_OnDataReceived(data)));

            SMQ_scaleClient.LogMessage += msg =>
                this.Invoke(new MethodInvoker(() => txtLog.AppendText($"[日志] {msg}{Environment.NewLine}")));

        }      

        private async void Main_Load(object sender, EventArgs e)
        {           
            config1.START(this);
            new PCHMI.AutoFormChange(this);//子窗口等比缩放
            pictureBox1.Image = imageList1.Images[0];
            pictureBox2.Image = imageList1.Images[0];
            textBox7.Text = Properties.Settings.Default.称重累计合格范围数值;
            comboBox1.Text = Properties.Settings.Default.称重累计合格范围符号;
            textBox_Name.Text = Properties.Settings.Default.员工名字;
            UIupdate(0);

            if (int.TryParse("1026", out int TC_port))
                await TC_scaleClient.TC_ConnectAsync("192.168.1.8", TC_port);
            else
                txtLog.AppendText("无效端口号");

            if (int.TryParse("55256", out int SMQ_port))
                await SMQ_scaleClient.SMQ_ConnectAsync("192.168.1.20", SMQ_port);
            else
                txtLog.AppendText("无效端口号");

            timer1.Start();
            timer2.Start();
            timer3.Start();
            
        }

        private void SMQ_OnDataReceived(string data)
        {
            // 处理接收到的条码数据
            Console.WriteLine($"接收到条码数据：{data}");
            if (textBox2.Enabled == true)
            {
                textBox2.Clear();
                try
                {
                    textBox2.Text = data.Replace("\r","").Split('=')[1].Replace(" ", "");
                    label15.Text = textBox2.Text;
                    textBox4.Text = Regex.Replace(textBox_Weight.Text, @"[^\d.\d]", "");
                    ;
                    if (textBox5.Text == textBox2.Text)
                    {
                        button_Sure2.Enabled = true;
                        pictureBox3.Image = imageList1.Images[2];
                        button_Sure2.Enabled = true;//新增
                    }
                    else
                    {
                        pictureBox3.Image = imageList1.Images[3];
                        button_Sure2.Enabled = false;//新增
                    }
                }
                catch (Exception ex) { MessageBox.Show("二维码错误！"); }
            }
            // 可以在此处添加更多逻辑，例如保存到数据库或调用其他功能
        }

        private void button_Save_Click(object sender, EventArgs e)
        {            
            I++;
            label_CumulativeNumber.Text = I.ToString();
            dataGridView1.Rows.Add();
            dataGridView1.Rows[I - 1].Cells[0].Value = I;
            dataGridView1.Rows[I - 1].Cells[1].Value = textBox_Name.Text;//新增员工名字到表格
            dataGridView1.Rows[I - 1].Cells[2].Value = label1.Text;
            dataGridView1.Rows[I - 1].Cells[3].Value = textBox_Batter.Text;//新增员工编号到表格
            dataGridView1.Rows[I - 1].Cells[4].Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");//新增时间到表格

            total_weight = 0;
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {

                total_weight = total_weight + float.Parse(dataGridView1.Rows[i].Cells[2].Value.ToString().Split('k')[0]);
            }
            label_CumulativeWeight.Text = total_weight.ToString("0.00") + "kg";
            JudgeWeightRange();
            Check();           
        }


       
        // 新增方法：将dataGridView1表格中的数据导入到excel表格的方法
        private void AppendDataToExcel()
        {
            string filePath = @"D:\date\exceldata\数据记录.xlsx";//可自定义路径
            try
            {
                FileInfo excelFile = new FileInfo(filePath);
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;             
                using (ExcelPackage package = new ExcelPackage(excelFile))
                {
                    ExcelWorksheet worksheet;

                    // 如果文件不存在或工作表不存在，创建新的
                    if (!excelFile.Exists || package.Workbook.Worksheets.Count == 0)
                    {
                        worksheet = package.Workbook.Worksheets.Add("数据记录");
                        // 添加表头（跳过第一列"次数"）
                        for (int i = 1; i < dataGridView1.Columns.Count; i++)
                        {
                            worksheet.Cells[1, i].Value = dataGridView1.Columns[i].HeaderText;
                        }
                    }
                    else
                    {
                        worksheet = package.Workbook.Worksheets[0];
                    }

                    // 找到最后一行（从第2行开始找空行）
                    int lastRow = 1;
                    while (worksheet.Cells[lastRow, 1].Value != null)
                    {
                        lastRow++;
                    }

                    // 如果lastRow为1，说明只有表头，数据从第2行开始
                    if (lastRow == 1) lastRow = 2;

                    // 导出数据（跳过第一列"次数"）
                    for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) // 跳过最后一行空行
                    {
                        for (int j = 1; j < dataGridView1.Columns.Count; j++) // 跳过第一列
                        {
                            object cellValue = dataGridView1.Rows[i].Cells[j].Value;
                            worksheet.Cells[lastRow, j].Value = cellValue?.ToString() ?? "";
                        }
                        lastRow++;
                    }

                    // 保存文件
                    package.Save();
                    MessageBox.Show($"数据已成功保存到：{filePath}", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //新增方法：“累计重量”到达某一条件时触发弹窗
        private void JudgeWeightRange()
        {
            try
            {
                string weight_str=label_CumulativeWeight.Text.Split('k')[0];
                double weight_de = double.Parse(weight_str);
                string WeighRange = label7.Text.Replace("kg", "");
                string[] weight_range=WeighRange.Split('~');
                double weight_min = double.Parse(weight_range[0]);
                double weight_max = double.Parse(weight_range[1]);

                if(weight_de>=weight_min&& weight_de<=weight_max&&!JudgeRange)
                {
                    MessageBox.Show("累计重量已到达合格区间", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    JudgeRange = true;
                }
                if (weight_de > weight_max && JudgeRange)
                {
                    MessageBox.Show("累计重量已超出合格区间,请核对确认", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    JudgeRange = false;
                }              
            }
            catch (Exception ex)
            {
                MessageBox.Show("合格区间设置错误！");
            }
        }
        

        //新增方法：“累计重量”在合格范围的判断
        private bool CheckWeight()
        {
            try
            {
                if(string.IsNullOrEmpty(label_CumulativeWeight.Text))
                    return false;
                string weight_str = label_CumulativeWeight.Text.Split('k')[0];//从label_CumulativeWeight中提取出重量的字符串
                if (!double.TryParse(weight_str,out double CumulativeWeight))//若转换为double类型失败则返回false
                    return false;

                string WeightRange= label7.Text.Replace("kg", "");//将label7中的单位去掉
                string[] weight_range = WeightRange.Split('~');//将WeightRange分割为上下限
                double weight_min = double.Parse(weight_range[0]);//提取最小值
                double weight_max = double.Parse(weight_range[1]);//提取最大值
               
                return CumulativeWeight >= weight_min&& CumulativeWeight<=weight_max;//判断是否在合格范围内

            }
            catch (Exception ex)
            {
                return false;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {
            PCHMI.RT.SET_INT16(0, "D102", 9);//INT16写入
            PCHMI.RT.SET_INT16(0, "D103", 100);//INT16写入
            PCHMI.RT.CTRL(0, "M140", "复位", "");

        }

        private void button5_Click(object sender, EventArgs e)
        {
            UIupdate(3);
        }

        private void UIupdate(int IMode)
        {
            switch (IMode)
            {
                case 0:
                    textBox2.Enabled = false;
                    textBox_Time.Enabled = false;
                    textBox5.Enabled = false;
                    textBox_Weight.Enabled = false;
                    button_Save.Enabled = false;
                    button2.Enabled = false;
                    button1.Enabled = false;
                    button_Sure2.Enabled = false;
                    button6.Enabled = false;
                    button7.Enabled = false;
                    button_Sure1.Enabled = false;
                    textBox_Batter.Text = "";
                    textBox2.Text = "";
                    textBox_Time.Text = "";
                    textBox4.Text = "";
                    textBox5.Text = "";
                    textBox_Weight.Text = "";
                    label15.Text = "";
                    label_CumulativeNumber.Text = "null";
                    label_CumulativeWeight.Text = "null";
                    dataGridView1.Rows.Clear();
                    timer3.Start();

                    break;
                case 1:
                    textBox_Time.Enabled = true;
                    textBox5.Enabled = true;
                    textBox_Weight.Enabled = true;

                    button7.Enabled = true;
                    button_Sure1.Enabled = true;
                    break;
                case 2:
                    textBox2.Enabled = true;
                    button_Sure2.Enabled = false;
                    button_Sure1.Enabled = false;
                    pictureBox3.Image = null;
                    button_Save.Enabled = false;
                    button2.Enabled = false;
                    button1.Enabled = false;
                    timer3.Stop();
                    break;
                case 3:
                    textBox2.Enabled = false;
                    button_Sure2.Enabled = false;
                    button6.Enabled = true;

                    button_Save.Enabled = false;
                    button2.Enabled = true;
                    button1.Enabled = true;
                    break;
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            UIupdate(2);
        }

        private async void button10_Click(object sender, EventArgs e)
        {

        }

        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            Properties.Settings.Default.称重累计合格范围数值 = textBox4.Text;
            Properties.Settings.Default.称重累计合格范围符号 = comboBox1.Text;
            Properties.Settings.Default.Save();
            TC_scaleClient.TC_Disconnect();
        }

        private async void button_RemovePeel_Click(object sender, EventArgs e)
        {
            await TC_scaleClient.TC_SendCommandAsync("T\r\n");
        }

        private async void timer1_Tick(object sender, EventArgs e)
        {
            // 根据台秤协议发送命令（示例命令）
            if (TC_scaleClient.TC_Reconnect())
            {   
                pictureBox2.Image = imageList1.Images[0];
                timer1.Interval = 10000;
                await TC_scaleClient.TC_ConnectAsync("192.168.1.8", 1026);
            }
            else
            {
                timer1.Interval = 1000;
                pictureBox2.Image = imageList1.Images[1];
                await TC_scaleClient.TC_SendCommandAsync("SI\r\n"); // 请求重量数据
            }
        }

        private async void button_ZeroClearing_Click(object sender, EventArgs e)
        {
            await TC_scaleClient.TC_SendCommandAsync("Z\r\n");
        }

        private async void button_ClearSkin_Click(object sender, EventArgs e)
        {
            await TC_scaleClient.TC_SendCommandAsync("TAC\r\n");
            label_Tare.Text = null;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            I = 0;
            label_CumulativeNumber.Text = "null";
            label_CumulativeWeight.Text = "null";
            dataGridView1.Rows.Clear();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            int a = dataGridView1.CurrentRow.Index;
            string RunProjectName = dataGridView1.Rows[a].Cells[0].Value.ToString();
            if (MessageBox.Show("确定删除第" + RunProjectName + "次数据", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                label_CumulativeNumber.Text = (int.Parse(label_CumulativeNumber.Text) - 1).ToString();
                dataGridView1.Rows.RemoveAt(a);

                total_weight = 0;
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    total_weight = total_weight + float.Parse(dataGridView1.Rows[i].Cells[2].Value.ToString().Split('k')[0]);
                }
                label_CumulativeWeight.Text = total_weight.ToString();

                //新增：判断是否在合格范围内
                CheckWeight();
                Check();
            }

            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                dataGridView1.Rows[i].Cells[0].Value = i + 1;
            }
            I--;
        }

        private async void timer2_Tick(object sender, EventArgs e)
        {
            if (SMQ_scaleClient.SMQ_Reconnect())
            {
                pictureBox1.Image = imageList1.Images[0];
                timer2.Interval = 10000;
                await SMQ_scaleClient.SMQ_ConnectAsync("192.168.1.20", 55256);
            }
            else
            {
                pictureBox1.Image = imageList1.Images[1];

            }
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            ChangePassword changePassword = new ChangePassword();
            changePassword.ShowDialog();
        }

        private void button10_Click_1(object sender, EventArgs e)
        {
            UserManagement userManagement = new UserManagement();
            userManagement.ShowDialog();
        }

        private void button12_Click(object sender, EventArgs e)
        {

        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            try
            {  
            switch (Properties.Settings.Default.称重累计合格范围符号)
            {
                case "±":
                    label7.Text = (double.Parse(textBox4.Text) * (100 - double.Parse(Properties.Settings.Default.称重累计合格范围数值)) / 100).ToString("0.00") + "~" + (double.Parse(textBox4.Text) * (100 + double.Parse(Properties.Settings.Default.称重累计合格范围数值)) / 100).ToString("0.00") + "kg";
                    break;
                case "+":
                    label7.Text = textBox4.Text + "~" + (double.Parse(textBox4.Text) * (100 + double.Parse(Properties.Settings.Default.称重累计合格范围数值)) / 100).ToString("0.00") + "kg";
                    break;
                case "-":
                    label7.Text = (double.Parse(textBox4.Text) * (100 - double.Parse(Properties.Settings.Default.称重累计合格范围数值)) / 100).ToString("0.00") + "~" + textBox4.Text + "kg";
                    break;
            }
            }catch
            { }
            }

        

        //新增功能：当输入框内容不为空时，按钮可用
        private void Check()
        {
            bool isTextBox8Valid = textBox_Name != null && !string.IsNullOrWhiteSpace(textBox_Name.Text);
            bool isTextBox1Valid = textBox_Batter != null && !string.IsNullOrWhiteSpace(textBox_Batter.Text);
            bool isWeighRangeValid = CheckWeight();

            button9.Enabled=isTextBox8Valid && isTextBox1Valid&& isWeighRangeValid;
            
            button_Save.Enabled = isTextBox8Valid && isTextBox1Valid;
        }

        private void button9_Click(object sender, EventArgs e)
        {
            AppendDataToExcel();

            PCHMI.RT.SET_INT16(0, "D102", 0);//INT16写入
            PCHMI.RT.SET_INT16(0, "D103", 0);//INT16写入

            //新增功能：发送重量信息给PLC 
            PCHMI.RT.SET_F32(0, "D200", total_weight);//FLOAT写入

            PCHMI.RT.CTRL(0, "M140", "置位", "");

           

            I = 0;
            label_CumulativeNumber.Text = "null";
            label_CumulativeWeight.Text = "null";
            dataGridView1.Rows.Clear();
            button9.Enabled = false;

            //button9.BackColor = Color.WhiteSmoke;

            // 创建保存文件对话框
            //using (SaveFileDialog saveFileDialog = new SaveFileDialog())
            //{
            //    // 设置对话框属性
            //    saveFileDialog.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*";
            //    saveFileDialog.Title = "保存文本文件";
            //    saveFileDialog.DefaultExt = "txt";
            //    saveFileDialog.AddExtension = true;
            //    saveFileDialog.FileName = "新建文本文件.txt";  // 默认文件名

            //    // 显示对话框并检查用户是否点击了"保存"
            //    if (saveFileDialog.ShowDialog() == DialogResult.OK)
            //    {
            //        try
            //        {
            //            // 获取用户输入的文件路径
            //            string filePath = saveFileDialog.FileName;

            //            // 这里替换为实际要保存的内容
            //            string contentToSave = "公司名称：" + label_CorporateName.Text
            //                + "\n批次号：" + textBox1.Text
            //                + "\n物料名称：" + label15.Text
            //                + "\n目标重量：" + textBox4.Text + "kg"
            //                + "\n称重累计合格范围：" + label7.Text
            //                + "\n累计次数：" + label_CumulativeNumber.Text
            //                + "\n累计重量：" + label_CumulativeWeight.Text
            //                + "\n第一次扫码结果：" + textBox2.Text
            //                ;

            //            // 将内容写入文件
            //            File.WriteAllText(filePath, contentToSave);

            //            MessageBox.Show($"文件保存成功！\n路径: {filePath}",
            //                            "保存成功",
            //                            MessageBoxButtons.OK,
            //                            MessageBoxIcon.Information);
            //        }
            //        catch (Exception ex)
            //        {
            //            MessageBox.Show($"保存文件时出错:\n{ex.Message}",
            //                            "错误",
            //                            MessageBoxButtons.OK,
            //                            MessageBoxIcon.Error);
            //        }
            //    }
            //}
        }


        private void button11_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("确定取消本次称重，取消后称重信息将清空！", "操作提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            if (result == DialogResult.OK)
            {
                UIupdate(0);
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            UIupdate(2);

        }

        private void button7_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("确定清空接收的称重信息，并重新接收！", "操作提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            if (result == DialogResult.OK)
            {
                UIupdate(0);
            }
        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            if (PCHMI.PClass.IsPlcLink(0))
            {
                pictureBox4.Image = imageList1.Images[1];
            }
            else
            {
                pictureBox4.Image = imageList1.Images[0];
            }

            if (PCHMI.RT.GET_INT16(0, "D102") > 0 && PCHMI.RT.GET_INT16(0, "D103") > 0)
            {
                DateTime currentTime = DateTime.Now;
                textBox_Time.Text = currentTime.ToString("yyyy.MM.dd hh:mm:ss");
                string str="";
                AAClass.AAMapping((int)PCHMI.RT.GET_INT16(0, "D102"), out str);
                textBox_Weight.Text = PCHMI.RT.GET_INT16(0, "D103").ToString() + "kg";
                textBox5.Text = str;
                PCHMI.RT.SET_INT16(0, "D102", 0);//INT16写入
                PCHMI.RT.SET_INT16(0, "D103", 0);//INT16写入
                PCHMI.RT.CTRL(0, "M140", "复位", "");

                UIupdate(1);
            }
        }

        

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.称重累计合格范围符号 = comboBox1.Text;
            Properties.Settings.Default.Save();
            try
            {
                switch (Properties.Settings.Default.称重累计合格范围符号)
                {
                    case "±":
                        label7.Text = (double.Parse(textBox4.Text) * (100 - double.Parse(Properties.Settings.Default.称重累计合格范围数值)) / 100).ToString("0.00") + "~" + (double.Parse(textBox4.Text) * (100 + double.Parse(Properties.Settings.Default.称重累计合格范围数值)) / 100).ToString("0.00") + "kg";
                        break;
                    case "+":
                        label7.Text = textBox4.Text + "~" + (double.Parse(textBox4.Text) * (100 + double.Parse(Properties.Settings.Default.称重累计合格范围数值)) / 100).ToString("0.00") + "kg";
                        break;
                    case "-":
                        label7.Text = (double.Parse(textBox4.Text) * (100 - double.Parse(Properties.Settings.Default.称重累计合格范围数值)) / 100).ToString("0.00") + "~" + textBox4.Text + "kg";
                        break;
                }
            }
            catch { }
            Check();
        }

        private void textBox8_TextChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.员工名字 = textBox_Name.Text;
            Properties.Settings.Default.Save();

        }

        private void textBox7_TextChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.称重累计合格范围数值 = textBox7.Text;
            Properties.Settings.Default.Save();

            try
            {
                switch (Properties.Settings.Default.称重累计合格范围符号)
                {
                    case "±":
                        label7.Text = (double.Parse(textBox4.Text) * (100 - double.Parse(Properties.Settings.Default.称重累计合格范围数值)) / 100).ToString("0.00") + "~" + (double.Parse(textBox4.Text) * (100 + double.Parse(Properties.Settings.Default.称重累计合格范围数值)) / 100).ToString("0.00") + "kg";
                        break;
                    case "+":
                        label7.Text = textBox4.Text + "~" + (double.Parse(textBox4.Text) * (100 + double.Parse(Properties.Settings.Default.称重累计合格范围数值)) / 100).ToString("0.00") + "kg";
                        break;
                    case "-":
                        label7.Text = (double.Parse(textBox4.Text) * (100 - double.Parse(Properties.Settings.Default.称重累计合格范围数值)) / 100).ToString("0.00") + "~" + textBox4.Text + "kg";
                        break;
                }
            }catch { }
        }
    }
}
